#pragma once

#include <iostream>
#include <unistd.h>
#include <sys/epoll.h>

#include "log.hpp"
#include "errno.hpp"

#define DEFAUTLEPOLL -1
class Epoll
{
public:
   Epoll(int epfd = DEFAUTLEPOLL)
   :_epfd(epfd)
   {}


   ~Epoll()
   {
      if(_epfd != DEFAUTLEPOLL) close(_epfd);
   }

public:
   void create()
   {
       _epfd = epoll_create(128);

       if(_epfd < 0)
       {
          logMessage(FATAL,"fail for create epfd");
          exit(EPOLL_CREATE_ERRON);
       }

       logMessage(SUCESS,"sucess for create epfd");
   }

   bool ctrlAdd(int socket , uint32_t event)
   {
      struct epoll_event ev;
      ev.events = event;
      ev.data.fd = socket;   
   
      int n = epoll_ctl(_epfd,EPOLL_CTL_ADD,socket,&ev);

      if(n < 0)
      {
          logMessage(WARNING,"fail for ctrlAdd epfd maybe the epfd is fill");
          return false;
      }
      
       logMessage(SUCESS,"sucess for ctrlAdd epfd");
       return true;
   }

   int wait(struct epoll_event* ev , int count , int timeout)
   {
       int n = epoll_wait(_epfd, ev , count , timeout);
       if( n < 0)
       {
         logMessage(WARNING,"epoll wait erron");
       }
       return n;
   }

   bool conTrol(int socket,uint32_t event, int macro)
   {
        int n = 0;
        if( macro == EPOLL_CTL_MOD)
        {
           struct epoll_event ev;
           ev.events = event;
           ev.data.fd = socket;

           n = epoll_ctl(_epfd,macro,socket,&ev);
        }
        else if(macro == EPOLL_CTL_DEL)
        {
           n= epoll_ctl(_epfd,macro,socket,nullptr);
        }
        else n = -1;

        return n == 0;
   }
    

private:
   int _epfd;
};